﻿using Kz.Telegram.Bot.Infrastructure.Extensions;
using Kz.Telegram.Bot.Infrastructure.Http;
using Microsoft.AspNetCore.Http;
using System.Net;

namespace Kz.Telegram.Bot.Infrastructure.Middlewares
{
    /// <summary>
    /// 全局处理中间件
    /// </summary>
    public class ExceptionHandleMiddleware
    {
        private readonly RequestDelegate _next;

        private readonly string _hubName;

        Action<Exception> ex_callback;

        public ExceptionHandleMiddleware(RequestDelegate next, Action<Exception> callback)
        {
            ex_callback = callback;
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }
            this._next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            Exception _exception = null;
            try
            {
                if (!context.Response.HasStarted)
                {
                    await _next(context);
                }
            }
            catch (Exception ex)
            {
                await Console.Out.WriteLineAsync(ex.ToJson());

                _exception = ex;

                var statusCode = context.Response.StatusCode;
                if (ex is ArgumentException)
                {
                    statusCode = 200;
                }
                else
                {
                    statusCode = (int)HttpStatusCode.InternalServerError;
                }
                await HandleExceptionAsync(context, statusCode, ex.Message);

                ex_callback?.Invoke(ex);
            }
            finally
            {
                var statusCode = context.Response.StatusCode;
                var msg = "";
                if (statusCode == 401)
                {
                    msg = "未授权";
                }
                else if (statusCode == 404)
                {
                    msg = "未找到服务";
                }
                else if (statusCode == 502)
                {
                    msg = "请求错误";
                }
                else if (statusCode == 500)
                {
                    ////通用异常处理
                    //_exception?.SubmitLess();
                    msg = "服务器内部错误";
                }
                else if (statusCode != 200)
                {
                    msg = "未知错误";
                }
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    await HandleExceptionAsync(context, statusCode, msg);
                }
            }
        }

        private static async Task HandleExceptionAsync(HttpContext context, int code, string msg)
        {
            var result = new ApiResponse((HttpStatusCode)code, msg).ToJson();

            if (!context.Response.HasStarted)
            {
                context.Response.ContentType = "application/json;charset=utf-8";
                await context.Response.WriteAsync(result);
            }
        }
    }
}